﻿using Basic.FormCollect;
using Basic.FormCollect.Model;
using Basic.FormModel;
using Basic.FormModel.PageLayout;
using Basic.FormModel.QueryColumn;
using Basic.FormRemoteModel;
using Basic.FormRemoteModel.PageLayout.DataTable;
using Basic.FormRemoteModel.PageLayout.Model;
using Basic.UserFormService.Interface;
using Basic.UserFormService.Model;
using WeDonekRpc.CacheClient.Interface;
using WeDonekRpc.Helper;
using WeDonekRpc.SqlSugar.VirtualQuery;

namespace Basic.UserFormService.PageControl
{
    internal class DataTableBodyCache
    {
        public DataTableBody Result { get; set; }
        /// <summary>
        /// 筛选条件
        /// </summary>
        public PageFilterParam[] Where { get; set; }
    }
    internal class PageDataTableService : PageControlService, IPageDataTableService
    {
        private readonly ICustomPageLayoutCollect _Layout;
        private readonly IPhysicsQueryBodyCollect _QueryTable;
        private readonly ILocalCacheController _Cache;
        public PageDataTableService ( ICustomPageLayoutCollect layout,
            ILocalCacheController cache,
            IPhysicsQueryBodyCollect queryTable )
        {
            this._Cache = cache;
            this._Layout = layout;
            this._QueryTable = queryTable;
        }
        private DataTableControl _Control;

        private readonly List<PhyExtendCol> _Extends = new List<PhyExtendCol>();
        public DataTableBody Get ( long controlId, long companyId, Dictionary<string, string> extend )
        {
            string key = "DataTableBody_" + controlId;
            if ( !this._Cache.TryGet(key, out DataTableBodyCache body) )
            {
                body = this._Get(controlId);
                _ = this._Cache.Add(key, body, new TimeSpan(23, 0, 0));
            }
            if ( body.Result.Query == null )
            {
                return body.Result;
            }
            DataTableBody res = body.Result.Clone();
            res.Query.Where = body.Where.GetWhere(body.Result.Cols, companyId, extend);
            return res;
        }
        private DataTableBodyCache _Get ( long controlId )
        {
            PageLayoutDto layout = this._Layout.Get<PageLayoutDto>(controlId);
            if ( layout.ControlType != PageControlType.明细表 )
            {
                throw new ErrorException("form.page.control.type.error");
            }
            this._Control = layout.ControlConfig?.Table;
            if ( this._Control.TableId != 0 && !this._Control.ColumnId.IsNull() )
            {
                PhysicsFormBody body = this._QueryTable.Get(this._Control.FormId);
                base._InitTable(body, [this._Control.TableId]);
                PhysicsQueryTable table = this._table[this._Control.TableId];
                this._InitSelect(body, table);
            }
            return new DataTableBodyCache
            {
                Where = this._Control.Where,
                Result = new DataTableBody
                {
                    FormId = this._Control.FormId,
                    Id = controlId,
                    PageId = layout.PageId,
                    TableId = this._Control.TableId,
                    ExtendCol = this._Extends.ToArray(),
                    Query = this._Query,
                    Cols = this._Cols
                }
            };
        }

        private void _InitSelect ( PhysicsFormBody body, PhysicsQueryTable table )
        {
            List<SelectStruct> selects = new List<SelectStruct>(1 + this._Control.ColumnId.Length);
            selects.Add(new SelectStruct
            {
                Name = ConstDic.KeyColName,
                Func = QueryFuncType.None,
                Table = table.TableName
            });
            this._Control.ColumnId.ForEach(c =>
            {
                PhysicsQueryColumn col = this._column[c];
                if ( col.ShowMode == PhyColShowMode.Column )
                {
                    selects.Add(new SelectStruct
                    {
                        Name = col.ColName,
                        Func = QueryFuncType.None,
                        Table = table.TableName
                    });
                }
                else if ( !this._Control.ColumnId.Contains(col.SourceCol.Value) )
                {
                    PhyExtendCol extendCol = new PhyExtendCol
                    {
                        Mode = col.ShowMode,
                        Name = col.ColName,
                        Source = col.SourceCol.Value,
                        DictId = col.DictId
                    };
                    col = this._column[col.SourceCol.Value];
                    extendCol.ColName = col.ColName;
                    this._Extends.Add(extendCol);
                    selects.Add(new SelectStruct
                    {
                        Name = col.ColName,
                        Func = QueryFuncType.None,
                        Table = table.TableName
                    });
                }
            });
            this._Query.Select = selects.ToArray();
        }

    }
}